//
//  LoginVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/10.
//

import UIKit
import Localize_Swift

var MHHYCrossImSensitiveWords = "MHHYCrossImSensitiveWords"
var MHHYCrossImBlacklist = "MHHYCrossImBlacklist"
var MHHYCrossLoginConfig = "MHHYCrossLoginConfig"
var MHHYCrossRefreshToken = "MHHYCrossRefreshToken"
let kScreenHeight = UIScreen.main.bounds.size.height
let kScreenWidth = UIScreen.main.bounds.size.width

typealias CompletionHandler = (Result<[String], Error>?) -> Void

func KLocalizedString(_ key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

class LoginVC: BaseVC,UITextFieldDelegate {
    func userAgreementViewButtonClick(_ tag: Int) {
        
    }
    
    
    private var times: Int = 0
    var logDic: [String: Any]?
    var timer: Timer?
    
    @IBOutlet weak var img: UIButton!
    
    @IBOutlet weak var loginBtn: UIButton! //验证码登录
    @IBOutlet weak var accLoginBtn: UIButton! //账号登录
    @IBOutlet weak var accView: UIView!
    @IBOutlet weak var pwdView: UIView!
    @IBOutlet weak var logoImageView: UIImageView!
    @IBOutlet weak var loginSendCodeBtn: UIButton! //获取验证码
    
    
    @IBOutlet weak var accountTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var LoginRegisterBtn: UIButton!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        
        if !UserDefaults.standard.bool(forKey: "isFirstLaunch") {
            getDapps()
            UserDefaults.standard.setValue(true, forKey: "isFirstLaunch")
            setPage()
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()

//        let isAgree = UserDefaults.standard.bool(forKey: "AgreeUserAgreement")
//        if !isAgree {
//            showMHHYUserAgreementView()
//        }

        accView.layer.cornerRadius = 10
        accView.layer.borderWidth = 1
        accView.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        
        pwdView.layer.cornerRadius = 10
        pwdView.layer.borderWidth = 1
        pwdView.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        
        loginBtn.layer.cornerRadius = 10
        accLoginBtn.layer.cornerRadius = 10
        logoImageView.layer.cornerRadius = 10
        loginSendCodeBtn.layer.cornerRadius = 5
        accountTextField.text = ""

        accountTextField.delegate = self
        passwordTextField.delegate = self
//            registerAccountTextField.delegate = self
//            registerPasswordTextField.delegate = self
//            registerConfirmTextField.delegate = self
//            registerCodeTextField.delegate = self
//            forgetAccoutTextField.delegate = self
//            forgetPasswordTextField.delegate = self
//            forgetConfirmPswTextField.delegate = self
//            forgetCodeTextField.delegate = self
        img.isSelected = true

        loginBtn.setTitle("LoginBtnText".localized(), for: .normal)
        loginSendCodeBtn.setTitle("SendCodeBtnText".localized(), for: .normal)
        LoginRegisterBtn.setTitle("LoginNewUserRegistration".localized(), for: .normal)
        passwordTextField.isSecureTextEntry = true

        setTextFieldAttributedPlaceholder(textField: accountTextField, withString: "PhoneNumberText".localized())
        setTextFieldAttributedPlaceholder(textField: passwordTextField, withString: "CodeText".localized())
    }
    
    func getDapps () {
        // 创建URL对象
        let url = "https://itunes.apple.com/lookup?id=6670187575"
        if let url = URL(string: url) {
            // 创建URLSessionDataTask
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

            }
            
            // 启动任务
            task.resume()
        }
    }
    
    // MARK: - 静态图片引导页
    func setPage() {
        let imageNameArray: [String] = ["bg1", "bg2", "bg3"]
        let guideView = HHGuidePageHUD.init(imageNameArray: imageNameArray, isHiddenSkipButton: false)
        self.navigationController?.view.addSubview(guideView)
    }
    
    @IBAction func selectImg(_ sender: Any) {
        self.img.isSelected = !self.img.isSelected
    }
    
    @IBAction func clickPrivacy(_ sender: Any) {
        
        self.navigationController?.pushViewController(PrivacyWebVC(string: "http://www.tjlm.top/app-page/privacy-policy.html"), animated: true)
    }
    

    //验证码登录
    @IBAction func login(_ sender: UIButton) {
        
        if !img.isSelected  {
            MHAlert.showMessage("请阅读并同意《悦聊隐私政策》")
            return
        }
        
        guard let accountText = accountTextField.text, !accountText.isEmpty else {
            MHAlert.showMessage("InputAccnout".localized())
            return
        }

        guard isValidPhoneNumber(phoneNumber: accountText) else {
            MHAlert.showMessage( "AccountError".localized())
            return
        }

        guard let passwordText = passwordTextField.text, !passwordText.isEmpty else {
            MHAlert.showMessage("InputCode")
            return
        }
        SVProgressHUD.show()
        Task{
            let (_, err) = await gosnLogin.loginWithCode(accountText, passwordText)
            
            await MainActor.run {
                SVProgressHUD.dismiss()
                if err != nil {
                    MHAlert.showMessage("\(err!.description)")
                }else{
                    Task {
                        if let deviceToken = UserDefaults.standard.object(forKey:"deviceToken") {
                            _ = await ghttpService.requestDeviceToken(deviceToken as! String)
                        }
                    }
                    InfoManager.shared.tabbar = TabBar()
                    UIApplication.shared.keyWindow?.rootViewController = InfoManager.shared.tabbar
                    MHAlert.showMessage(KLocalizedString("登录成功"))
                }
            }
            
            
        }
    }
    
    //账号登录
    @IBAction func accLogin(_ sender: Any) {
        if !img.isSelected  {
            MHAlert.showMessage("请阅读并同意《悦聊隐私政策》")
            return
        }
        self.presentVC(VC: AccountLoginVC())
    }
    
    @IBAction func getCode(_ sender: Any) {//获取验证码
        guard let accountText = accountTextField.text, !accountText.isEmpty else {
            MHAlert.showMessage("InputAccnout".localized())
            return
        }

        guard isValidPhoneNumber(phoneNumber: accountText) else {
            MHAlert.showMessage( "AccountError".localized())
            return
        }
        SVProgressHUD.show()
        Task {
            let (res, err) = await gosnLogin.getCode(accountText,2)
            await MainActor.run {
                SVProgressHUD.dismiss()
                if err == nil {
                    MHAlert.showMessage(KLocalizedString("CodeSendSuccess"))
                    self.changeSendCodeStatus()
                }else{
                    MHAlert.showMessage("\(err!.description)")
                }
            }
        }
    }
    @IBAction func registerClick(_ sender: Any) {//注册
        self.presentVC(VC: RegisterVC())
    }
    
    
    func changeSendCodeStatus() {
        loginSendCodeBtn.isEnabled = false
        times = 60
        loginSendCodeBtn!.endEditing(false)
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
//        Timer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }
    
    @objc func timerAction() {
        times -= 1
        loginSendCodeBtn!.setTitle("(\(times)s)", for: .normal)
        
        if times <= 0 {
            timer?.invalidate()
            timer = nil
            loginSendCodeBtn.setTitle(NSLocalizedString("SendCodeBtnText", comment: ""), for: .normal)
            loginSendCodeBtn.isEnabled = true
        }else {
            loginSendCodeBtn.isEnabled = false
        }
    }
    
//    func showMHHYUserAgreementView() {
//          guard let nib = Bundle.main.loadNibNamed("UserAgreView", owner: self, options: nil)?.first as? UserAgreView else {
//              fatalError("Failed to load MHHYUserAgreementView")
//          }
//          
//          userAgreementView = nib
//          userAgreementView?.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
//          userAgreementView?.delegate = self
//          userAgreementView?.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.3)
//          
//          UIApplication.shared.keyWindow?.addSubview(userAgreementView!)
//      }

        func setTextFieldAttributedPlaceholder(textField: UITextField, withString string: String) {
            let placeholder = NSAttributedString(string: string, attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])
            textField.attributedPlaceholder = placeholder
        }

        // 导航到网页视图
    func pushWebViewWithUrlString(_ urlStr: String) {
//            let vc = MHHYUserPrivacyWebVC()
//            vc.urlStr = urlStr
//            navigationController?.pushViewController(vc, animated: true)
        }

        // 通用刷新UI方法
        func refreshUI() {
            accountTextField.text = ""
            passwordTextField.text = ""
//            forgetAccoutTextField.text = ""
//            forgetPasswordTextField.text = ""
//            forgetConfirmPswTextField.text = ""
//            forgetCodeTextField.text = ""
//            registerAccountTextField.text = ""
//            registerPasswordTextField.text = ""
//            registerConfirmTextField.text = ""
//            registerCodeTextField.text = ""

            loginSendCodeBtn.isEnabled = true
//            registerGetCodeBtn.isEnabled = true
//            forgetSendCodeBtn.isEnabled = true
            
            loginSendCodeBtn.setTitle("SendCodeBtnText", for: .normal)
//            registerGetCodeBtn.setTitle("SendCodeBtnText", for: .normal)
//            forgetSendCodeBtn.setTitle("SendCodeBtnText", for: .normal)
        }

        // 设置文本字段属性占位符
        func setTextFieldAttributedPlaceholder(textField: UITextField, string: String) {
            let attributedPlaceholder = NSAttributedString(string: string, attributes: [
                NSAttributedString.Key.foregroundColor: UIColor.black,
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0)
            ])
            textField.attributedPlaceholder = attributedPlaceholder
        }

        // 文本字段代理方法 - 当文本字段应该返回时
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            accountTextField.resignFirstResponder()
            passwordTextField.resignFirstResponder()
//            registerAccountTextField.resignFirstResponder()
//            registerPasswordTextField.resignFirstResponder()
//            registerConfirmTextField.resignFirstResponder()
//            registerCodeTextField.resignFirstResponder()
//            forgetAccoutTextField.resignFirstResponder()
//            forgetPasswordTextField.resignFirstResponder()
//            forgetConfirmPswTextField.resignFirstResponder()
//            forgetCodeTextField.resignFirstResponder()
            return true
        }

        // 文本字段代理方法 - 当文本字段应该改变字符范围时
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if string == "\n" {
                textField.resignFirstResponder()
                return false
            } else if string.isEmpty {
                return true
            }
            return true
        }

        


    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    deinit {
        self.timer?.invalidate()
        self.timer = nil
    }
    
}




